Passed
Pull Request — master (#45)
by
unknown
06:19
created

button.js ➔ toggle   D

Complexity

Conditions 12

Size

Total Lines 47
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 26
dl 0
loc 47
rs 4.8
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like button.js ➔ toggle often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
/*!
2
  * Bootstrap button.js v4.5.3 (https://getbootstrap.com/)
3
  * Copyright 2011-2020 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)
4
  * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
5
  */
6
(function (global, factory) {
7
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('jquery')) :
8
  typeof define === 'function' && define.amd ? define(['jquery'], factory) :
0 ignored issues
show
Bug introduced by
The variable define seems to be never declared. If this is a global, consider adding a /** global: define */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
9
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Button = factory(global.jQuery));
0 ignored issues
show
Best Practice introduced by
If you intend to check if the variable self is declared in the current environment, consider using typeof self === "undefined" instead. This is safe if the variable is not actually declared.
Loading history...
Comprehensibility introduced by
Usage of the sequence operator is discouraged, since it may lead to obfuscated code.

The sequence or comma operator allows the inclusion of multiple expressions where only is permitted. The result of the sequence is the value of the last expression.

This operator is most often used in for statements.

Used in another places it can make code hard to read, especially when people do not realize it even exists as a seperate operator.

This check looks for usage of the sequence operator in locations where it is not necessary and could be replaced by a series of expressions or statements.

var a,b,c;

a = 1, b = 1,  c= 3;

could just as well be written as:

var a,b,c;

a = 1;
b = 1;
c = 3;

To learn more about the sequence operator, please refer to the MDN.

Loading history...
Bug introduced by
The variable globalThis seems to be never declared. If this is a global, consider adding a /** global: globalThis */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
10
}(this, (function ($) { 'use strict';
11
12
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
13
14
  var $__default = /*#__PURE__*/_interopDefaultLegacy($);
15
16
  function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
17
18
  function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
19
  /**
20
   * ------------------------------------------------------------------------
21
   * Constants
22
   * ------------------------------------------------------------------------
23
   */
24
25
  var NAME = 'button';
26
  var VERSION = '4.5.3';
27
  var DATA_KEY = 'bs.button';
28
  var EVENT_KEY = "." + DATA_KEY;
29
  var DATA_API_KEY = '.data-api';
30
  var JQUERY_NO_CONFLICT = $__default['default'].fn[NAME];
31
  var CLASS_NAME_ACTIVE = 'active';
32
  var CLASS_NAME_BUTTON = 'btn';
33
  var CLASS_NAME_FOCUS = 'focus';
34
  var SELECTOR_DATA_TOGGLE_CARROT = '[data-toggle^="button"]';
35
  var SELECTOR_DATA_TOGGLES = '[data-toggle="buttons"]';
36
  var SELECTOR_DATA_TOGGLE = '[data-toggle="button"]';
37
  var SELECTOR_DATA_TOGGLES_BUTTONS = '[data-toggle="buttons"] .btn';
38
  var SELECTOR_INPUT = 'input:not([type="hidden"])';
39
  var SELECTOR_ACTIVE = '.active';
40
  var SELECTOR_BUTTON = '.btn';
41
  var EVENT_CLICK_DATA_API = "click" + EVENT_KEY + DATA_API_KEY;
42
  var EVENT_FOCUS_BLUR_DATA_API = "focus" + EVENT_KEY + DATA_API_KEY + " " + ("blur" + EVENT_KEY + DATA_API_KEY);
43
  var EVENT_LOAD_DATA_API = "load" + EVENT_KEY + DATA_API_KEY;
44
  /**
45
   * ------------------------------------------------------------------------
46
   * Class Definition
47
   * ------------------------------------------------------------------------
48
   */
49
50
  var Button = /*#__PURE__*/function () {
51
    function Button(element) {
52
      this._element = element;
53
      this.shouldAvoidTriggerChange = false;
54
    } // Getters
55
56
57
    var _proto = Button.prototype;
58
59
    // Public
60
    _proto.toggle = function toggle() {
61
      var triggerChangeEvent = true;
62
      var addAriaPressed = true;
63
      var rootElement = $__default['default'](this._element).closest(SELECTOR_DATA_TOGGLES)[0];
64
65
      if (rootElement) {
66
        var input = this._element.querySelector(SELECTOR_INPUT);
67
68
        if (input) {
69
          if (input.type === 'radio') {
70
            if (input.checked && this._element.classList.contains(CLASS_NAME_ACTIVE)) {
71
              triggerChangeEvent = false;
72
            } else {
73
              var activeElement = rootElement.querySelector(SELECTOR_ACTIVE);
74
75
              if (activeElement) {
76
                $__default['default'](activeElement).removeClass(CLASS_NAME_ACTIVE);
77
              }
78
            }
79
          }
80
81
          if (triggerChangeEvent) {
82
            // if it's not a radio button or checkbox don't add a pointless/invalid checked property to the input
83
            if (input.type === 'checkbox' || input.type === 'radio') {
84
              input.checked = !this._element.classList.contains(CLASS_NAME_ACTIVE);
85
            }
86
87
            if (!this.shouldAvoidTriggerChange) {
88
              $__default['default'](input).trigger('change');
89
            }
90
          }
91
92
          input.focus();
93
          addAriaPressed = false;
94
        }
95
      }
96
97
      if (!(this._element.hasAttribute('disabled') || this._element.classList.contains('disabled'))) {
98
        if (addAriaPressed) {
99
          this._element.setAttribute('aria-pressed', !this._element.classList.contains(CLASS_NAME_ACTIVE));
100
        }
101
102
        if (triggerChangeEvent) {
103
          $__default['default'](this._element).toggleClass(CLASS_NAME_ACTIVE);
104
        }
105
      }
106
    };
107
108
    _proto.dispose = function dispose() {
109
      $__default['default'].removeData(this._element, DATA_KEY);
110
      this._element = null;
111
    } // Static
112
    ;
113
114
    Button._jQueryInterface = function _jQueryInterface(config, avoidTriggerChange) {
115
      return this.each(function () {
116
        var $element = $__default['default'](this);
117
        var data = $element.data(DATA_KEY);
118
119
        if (!data) {
120
          data = new Button(this);
121
          $element.data(DATA_KEY, data);
122
        }
123
124
        data.shouldAvoidTriggerChange = avoidTriggerChange;
125
126
        if (config === 'toggle') {
127
          data[config]();
128
        }
129
      });
130
    };
131
132
    _createClass(Button, null, [{
133
      key: "VERSION",
134
      get: function get() {
135
        return VERSION;
136
      }
137
    }]);
138
139
    return Button;
140
  }();
141
  /**
142
   * ------------------------------------------------------------------------
143
   * Data Api implementation
144
   * ------------------------------------------------------------------------
145
   */
146
147
148
  $__default['default'](document).on(EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE_CARROT, function (event) {
149
    var button = event.target;
150
    var initialButton = button;
151
152
    if (!$__default['default'](button).hasClass(CLASS_NAME_BUTTON)) {
153
      button = $__default['default'](button).closest(SELECTOR_BUTTON)[0];
154
    }
155
156
    if (!button || button.hasAttribute('disabled') || button.classList.contains('disabled')) {
157
      event.preventDefault(); // work around Firefox bug #1540995
158
    } else {
159
      var inputBtn = button.querySelector(SELECTOR_INPUT);
160
161
      if (inputBtn && (inputBtn.hasAttribute('disabled') || inputBtn.classList.contains('disabled'))) {
162
        event.preventDefault(); // work around Firefox bug #1540995
163
164
        return;
165
      }
166
167
      if (initialButton.tagName === 'INPUT' || button.tagName !== 'LABEL') {
168
        Button._jQueryInterface.call($__default['default'](button), 'toggle', initialButton.tagName === 'INPUT');
169
      }
170
    }
171
  }).on(EVENT_FOCUS_BLUR_DATA_API, SELECTOR_DATA_TOGGLE_CARROT, function (event) {
172
    var button = $__default['default'](event.target).closest(SELECTOR_BUTTON)[0];
173
    $__default['default'](button).toggleClass(CLASS_NAME_FOCUS, /^focus(in)?$/.test(event.type));
174
  });
175
  $__default['default'](window).on(EVENT_LOAD_DATA_API, function () {
176
    // ensure correct active class is set to match the controls' actual values/states
177
    // find all checkboxes/readio buttons inside data-toggle groups
178
    var buttons = [].slice.call(document.querySelectorAll(SELECTOR_DATA_TOGGLES_BUTTONS));
179
180
    for (var i = 0, len = buttons.length; i < len; i++) {
181
      var button = buttons[i];
182
      var input = button.querySelector(SELECTOR_INPUT);
183
184
      if (input.checked || input.hasAttribute('checked')) {
185
        button.classList.add(CLASS_NAME_ACTIVE);
186
      } else {
187
        button.classList.remove(CLASS_NAME_ACTIVE);
188
      }
189
    } // find all button toggles
190
191
192
    buttons = [].slice.call(document.querySelectorAll(SELECTOR_DATA_TOGGLE));
193
194
    for (var _i = 0, _len = buttons.length; _i < _len; _i++) {
195
      var _button = buttons[_i];
196
197
      if (_button.getAttribute('aria-pressed') === 'true') {
198
        _button.classList.add(CLASS_NAME_ACTIVE);
199
      } else {
200
        _button.classList.remove(CLASS_NAME_ACTIVE);
201
      }
202
    }
203
  });
204
  /**
205
   * ------------------------------------------------------------------------
206
   * jQuery
207
   * ------------------------------------------------------------------------
208
   */
209
210
  $__default['default'].fn[NAME] = Button._jQueryInterface;
211
  $__default['default'].fn[NAME].Constructor = Button;
212
213
  $__default['default'].fn[NAME].noConflict = function () {
214
    $__default['default'].fn[NAME] = JQUERY_NO_CONFLICT;
215
    return Button._jQueryInterface;
216
  };
217
218
  return Button;
219
220
})));
221
//# sourceMappingURL=button.js.map
222